package com.example.mydemoproject.controller;

import com.example.mydemoproject.model.entity.RollBaclDemo;
import com.example.mydemoproject.model.response.Result;
import com.example.mydemoproject.service.rollback.MultithreadingRollBackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/multithreadingRollBack")
@Slf4j
@Api(tags = "多线程事务回滚测试接口")
@RequiredArgsConstructor
public class MultithreadingRollBackController {

    private final MultithreadingRollBackService multithreadingRollBackService;

    @GetMapping("/saveThreadHaveErr")
    @ApiOperation(value = "测试多线程插入数据失败自动事务回滚")
    public Result<Object> saveThreadHaveErr() {
        List<RollBaclDemo> list = createList();
        multithreadingRollBackService.saveThreadHaveErr(list);
        return Result.OK();
    }

    @GetMapping("/saveThread")
    @ApiOperation(value = "测试多线程插入数据手动事务回滚")
    public Result<Object> saveThread() {
        List<RollBaclDemo> list = createList();
        multithreadingRollBackService.saveThread(list);
        return Result.OK();
    }

    @GetMapping("/save")
    @ApiOperation(value = "单线程插入数据")
    public Result<Object> save() {
        List<RollBaclDemo> list = createList();
        for (RollBaclDemo rollBaclDemo : list) {
            multithreadingRollBackService.save(rollBaclDemo);
        }
        return Result.OK();
    }

    private List<RollBaclDemo> createList() {
        List<RollBaclDemo> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            RollBaclDemo rollBaclDemo = new RollBaclDemo();
            rollBaclDemo.setName(UUID.randomUUID().toString());
            list.add(rollBaclDemo);
        }
        return list;
    }

}
